// SPDX-FileCopyrightText: 2020 Kent Gibson <warthog618@gmail.com>
//
// SPDX-License-Identifier: MIT

//go:build linux

// A simple example that reads an input pin.
package main

import (
	"flag"
	"io"
	"log"
	"os"
	"strconv"
	"strings"
	"time"
)

func getCpuTemp() (v float64, err error) {
	data, err := os.ReadFile("/sys/class/thermal/thermal_zone0/temp")
	if err != nil {
		return
	}
	val := strings.TrimSpace(string(data))
	v, err = strconv.ParseFloat(val, 64)
	if err != nil {
		return
	}
	v /= 1000
	return
}

func main() {
	var temp = flag.Float64("temp", 50, "高温阈值")
	var noLog = flag.Bool("nolog", false, "是否禁用日志输出")
	flag.Parse()
	if *noLog {
		log.SetOutput(io.Discard)
	}
	//pin12 输出 控制水泵
	//pin16 输入 检测水位是否缺水
	pinWaterStage, err := NewDI(pin16.Chip, pin16.Offset)
	if err != nil {
		log.Println(err)
		return
	}
	defer pinWaterStage.Close()
	pinPump, err := NewDO(pin12.Chip, pin12.Offset)
	if err != nil {
		log.Println(err)
		return
	}
	defer pinPump.Close()

	lastSetTime := time.Now().Unix()
	for {
		time.Sleep(time.Second)
		waterState, err := pinWaterStage.Value()
		if err != nil {
			log.Println(err)
			return
		}

		pumpStatus, err := pinPump.Value()
		if err != nil {
			log.Println(err)
			return
		}

		cpuTemp, err := getCpuTemp()
		if err != nil {
			log.Println(err)
			continue
		}

		if cpuTemp >= (*temp) {
			if waterState == 1 {
				if pumpStatus != 1 {
					pinPump.Set(1)
					log.Printf("水泵运行: %d, 水位正常: %d, CPU温度: %.2f", pumpStatus, waterState, cpuTemp)
					time.Sleep(time.Second * 30)
					continue
				}
			}
		}
		if time.Now().Unix()-lastSetTime > 8*3600 {
			if pumpStatus == 0 {
				pinPump.Set(1)
				log.Printf("水泵运行: %d, 水位正常: %d, CPU温度: %.2f", pumpStatus, waterState, cpuTemp)
				time.Sleep(time.Second * 20)
				pinPump.Set(0)
				lastSetTime = time.Now().Unix()
				continue
			}
		}
		if pumpStatus == 1 {
			pinPump.Set(0)
			lastSetTime = time.Now().Unix()
		}
		log.Printf("水泵运行: %d, 水位正常: %d, CPU温度: %.2f", pumpStatus, waterState, cpuTemp)
	}
}
